package com.m3958.firstgwt.server.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import redis.clients.jedis.Jedis;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.m3958.firstgwt.server.constants.PeriodContants;
import com.m3958.firstgwt.server.service.AppUtilService;
import com.m3958.firstgwt.server.service.JedisPoolService;
import com.m3958.firstgwt.server.service.MySHAService;

@Singleton
public class CombServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	private MySHAService shaService;
	
	@Inject
	private AppUtilService autils;
	
	private Pattern hostipPattern = Pattern.compile("(.*)(&.*)(&.*)");
	
	@Inject
	private JedisPoolService jedis;
	
	//BASE + VERSION + '/build/',
	//http://yui.yahooapis.com/combo?3.4.1/build/oop/oop-min.js&3.4.1/build/event-custom-base/event-custom-base-min.js&3.4.1/build/event-custom-complex/event-custom-complex-min.js&3.4.1/build/attribute-base/attribute-base-min.js&3.4.1/build/base-base/base-base-min.js&3.4.1/build/pluginhost-base/pluginhost-base-min.js&3.4.1/build/pluginhost-config/pluginhost-config-min.js&3.4.1/build/base-pluginhost/base-pluginhost-min.js&3.4.1/build/base-build/base-build-min.js&3.4.1/build/jsonp/jsonp-min.js&3.4.1/build/jsonp-url/jsonp-url-min.js&3.4.1/build/dump/dump-min.js&3.4.1/build/dom-core/dom-core-min.js&3.4.1/build/dom-base/dom-base-min.js&3.4.1/build/selector-native/selector-native-min.js&3.4.1/build/selector/selector-min.js&3.4.1/build/node-core/node-core-min.js&3.4.1/build/node-base/node-base-min.js&3.4.1/build/event-base/event-base-min.js&3.4.1/build/event-delegate/event-delegate-min.js&3.4.1/build/node-event-delegate/node-event-delegate-min.js&3.4.1/build/node-pluginhost/node-pluginhost-min.js&3.4.1/build/dom-style/dom-style-min.js&3.4.1/build/dom-screen/dom-screen-min.js&3.4.1/build/node-screen/node-screen-min.js&3.4.1/build/node-style/node-style-min.js&3.4.1/build/intl/intl-min.js
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		String qs = req.getQueryString();//调试模式下是null，服务器一侧不可能null。

		ArrayList<String> qfiles = new ArrayList<String>();
		StringBuffer jk = new StringBuffer();
		if(qs != null){
			String[] qsItems = qs.split("&");
			for(String fn :qsItems){
				if(fn.startsWith("hostname=") || fn.startsWith("remoteip=")){
					;
				}else{
					qfiles.add(fn);
					jk.append(fn);
				}
			}
		}
		String jks = jk.toString();
		String mimeType = null;
		if(qfiles.isEmpty()){
			;
		}else{
			String firstqf = qfiles.get(0); 
			if(firstqf.endsWith(".js")){
				mimeType = "text/javascript";
			}else if(firstqf.endsWith(".css")){
				mimeType =  "text/css";
			}
		}
		
		
		
		if(mimeType == null || mimeType.isEmpty())mimeType = "text/javascript";
		res.setContentType(mimeType + ";charset=utf-8");   
		res.setCharacterEncoding("UTF-8");
		Writer out = res.getWriter();
		
		
		String jss = null;
		Jedis jd = jedis.getInstance();
		try {
			jss = jd.get(jks);
		} catch (Exception e1) {
		}
		
		if(jks.endsWith("|||")){//用来删除jedis的标记
			String k = jks.substring(0, jks.length() - 3);
			jd.del(k);
		}

		
		if(jss != null){
			res.setContentLength(jss.length());
			out.write(jss);
		}else{
			String[] rp = req.getRequestURI().split("/");
			File wr = null;
			if(rp.length == 3){
				wr = new File(getServletContext().getRealPath("/" + rp[2]));
				res.setHeader("Cache-Control","max-age=51840000" );//60天
			}else{
				wr = new File(getServletContext().getRealPath("/"));
			}
			 
			StringBuffer js = new StringBuffer();
			for(String fn : qfiles){
				File f = null;
				f = new File(wr,fn);
				if(f != null && f.isFile() && f.exists()){
					try {
						FileInputStream is = new FileInputStream(f);
						String s = autils.read2String(is, "utf-8");
						js.append(s);
						out.write(s);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			if(jd != null){
				jd.set(jks,js.toString());
				jd.expire(jks, PeriodContants.MONTH_IN_SECONDS * 3);
			}
		}
		out.flush();
		out.close();
	}
}
